/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package docmanager.db;

import bf.DataAccess;
import bf.Logger;

import java.sql.*;
/**
 *
 * @author Juan Lucas
 */
public class ConnectionPool
{
   
  
    private static ConfigData cd = null;
    private static int cantidadConn  = 0;
    


    private static Connection armarConexion()
            throws SQLException
    {
        try
        {
          Class.forName (cd.getDBdriver()).newInstance ();
        } catch (Exception ex)
        {
            System.out.println("PROBLEMAS");
 //           ex.printStackTrace();
           // return null;
//Se tira excepcion pero no hacer caso.
        }
        Connection conn = DriverManager.getConnection (cd.getUrl() +cd.getDataBaseName(), 
                cd.getDBlogin(), cd.getDBpassword());
        return(conn);
    }
    
    
    public static Connection getConnection()
            throws SQLException
    {
        if (ConnectionPool.cd == null)
        {
           ConnectionPool.cd = ConfigData.getInstance();
           
        }
        Connection conn;
        System.out.println("CP: cantidadConn: " + ConnectionPool.cantidadConn 
                +" Maximo: " + cd.getMaxConnections() );
        if (ConnectionPool.cantidadConn < cd.getMaxConnections())
        {
            conn = ConnectionPool.armarConexion();
            ConnectionPool.cantidadConn++;
        }
        else
        {
        	Logger.logM(Logger.GRAVE, "El pool de conexiones se ha agotado.");
        	conn = null;
        }
        
        return conn;
    }
    
    public static void closeConn(Connection conn) throws SQLException
    {
        conn.close();
        ConnectionPool.cantidadConn--;
    }
    
}
